package com.hzdl.car.service.impl;

import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.hzdl.car.bean.Menu;
import com.hzdl.car.bean.Role;
import com.hzdl.car.bean.User;
import com.hzdl.car.mapper.RoleMapper;
import com.hzdl.car.mapper.UserMapper;
import com.hzdl.car.service.UserService;
import com.hzdl.car.util.SysConstast;
import com.hzdl.car.vo.RoleVo;
import com.hzdl.car.vo.UserVo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Service
public class UserServiceImpl implements UserService {

    @Autowired
    private UserMapper um;
    @Autowired
    private RoleMapper rm;
    @Override
    public User findUser(UserVo uservo) {
        return um.findUser(uservo);
    }

    @Override
    public PageInfo findByWhere(UserVo userVo) {
        PageHelper.startPage(userVo.getPage(),userVo.getLimit());
        List<User> uList = um.findByWhere(userVo);
        PageInfo pageInfo = new PageInfo(uList);
        return pageInfo;
    }
    @Override
    public List<Map<String,Object>> findRole(Integer uid) {

    RoleVo roleVo = new RoleVo();
    roleVo.setAvailable(SysConstast.AVAILABLE_TRUE);
    // 查询所有的角色
    List<Role> allRole = rm.findByWhere(roleVo);

    // 获取当前用户的角色
    List<Role> userRole = um.findRoleByUserId(uid);
    // 设置LAY_CHECKED为true，页面上的checkbox就是选中状态了。

    List<Map<String,Object>> list = new ArrayList<>();


    for(Role role:allRole){
        Map<String,Object> map = new HashMap<>();
        boolean LAY_CHECKED = false;
        for (Role role1: userRole){
            if(role.getRoleid() == role1.getRoleid()){
                LAY_CHECKED = true;
                break;
            }
        }
        map.put("LAY_CHECKED",LAY_CHECKED);
        map.put("roleid",role.getRoleid());
        map.put("rolename",role.getRolename());
        map.put("roledesc",role.getRoledesc());
        list.add(map);
    }

    return list;
}

    @Override
    public int updateRoleUser(UserVo userVo) {
        // 修改用户的角色
        // x先删除当前用户所有的角色
        int row = um.deleteRoleUserByUserId(userVo.getUserid());
        // 添加新角色
        row += um.addRoleUser(userVo);

        return row;
    }

    @Override
    public int addRoleUser(UserVo userVo) {
        return um.addRoleUserAll(userVo);
    }

    @Override
    public int updateUser(UserVo userVo) {
        return um.updateUser(userVo);
    }

    @Override
    public int deleteUser(UserVo userVo) {
        int row=um.deleteUserAndRole(userVo);
        row+=um.userDelete(userVo);
        return row;
    }

    @Override
    public int resetPwd(UserVo userVo) {
        return um.resetPwd(userVo);
    }

    @Override
    public List<Menu> findMenuByUserId(Integer userId) {
        return um.findMenuByUserId(userId);
    }

}
